import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

import '../../api/api_auth_center.dart';
import '../../core/auth/user_manager.dart';
import '../../exception/global_error_handler.dart';
import '../../route/route_utils.dart';
import '../../route/routes.dart';

class LogoutPage extends StatefulWidget {
  const LogoutPage({super.key});

  @override
  State<LogoutPage> createState() => _LogoutPageState();
}

class _LogoutPageState extends State<LogoutPage> {
  Future<void> _logout() async {
    try {
      var gsid = UserManager().session?.gsid;
      await ApiAuthCenter.api.logout(gsid!);
    } catch (e) {
      GlobalErrorHandler().handleError(e);
    } finally {
      if (mounted) {
        UserManager().clearAll();
        // 跳转到登录页并移除历史记录
        RouteUtils.pushNamedAndRemoveUntil(context, RoutePath.login);
      }
    }
  }

  void _showConfirmDialog() {
    final l10n = AppLocalizations.of(context)!;
    showDialog(
      context: context,
      builder: (_) => AlertDialog(
        title: Text(l10n.logoutConfirmTitle),
        content: Text(l10n.logoutConfirmMessage),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text(l10n.commonCancel),
          ),
          ElevatedButton(
            style: ElevatedButton.styleFrom(
              backgroundColor: Theme.of(context).colorScheme.error,
              foregroundColor: Colors.white,
            ),
            onPressed: () {
              Navigator.pop(context);
              _logout();
            },
            child: Text(l10n.logoutConfirmButton),
          ),
        ],
      ),
    );
  }

  Widget _buildSectionTitle(BuildContext context, String title) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(16, 24, 16, 8),
      child: Text(
        title,
        style: Theme.of(context).textTheme.titleSmall?.copyWith(
          color: Theme.of(context).colorScheme.primary,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    var profile = UserManager().profile;
    final l10n = AppLocalizations.of(context)!;
    return Scaffold(
      appBar: AppBar(title: Text(l10n.logoutSignOutTitle)),
      body: ListView(
        children: [
          _buildSectionTitle(context, l10n.logoutAccountInfo),
          Card(
            margin: const EdgeInsets.symmetric(horizontal: 12),
            child: ListTile(
              leading: const CircleAvatar(
                backgroundImage: AssetImage('assets/images/avatar.jpg'),
              ),
              title: Text(profile!.username),
              subtitle: Text(profile.phone ?? ""),
            ),
          ),
          _buildSectionTitle(context, l10n.logoutSecurityAction),
          Card(
            margin: const EdgeInsets.symmetric(horizontal: 12),
            child: ListTile(
              leading: Icon(Icons.logout,
                  color: Theme.of(context).colorScheme.error),
              title: Text(
                l10n.logoutSignOut,
                style: TextStyle(color: Theme.of(context).colorScheme.error),
              ),
              onTap: () => _showConfirmDialog(),
            ),
          ),
        ],
      ),
    );
  }
}
